var BARAKUS_PATH = '/application/BarakusUnite/';
var WEB_PATH = '/application/';

//INCLUDE LIBs
//__safe_file_get(BARAKUS_PATH + 'lib/uniteness.js', null);
//safe_file_get(BARAKUS_PATH + 'lib/simple-class.js', null);
//safe_file_get(BARAKUS_PATH + 'lib/php.js', null);
//__safe_file_get(BARAKUS_PATH + 'lib/____php.js', null);

Barakus = Class.extend({
	init: function(urlMap){
		var maps = [
			'_request', __barakus
		];
		
		for (map in urlMap)
		{
			maps.push(map);
		}
		
		URLs(maps);   
		
		this.request = null;
		this.io = null;
		this.rawRequest = null;
		this.actionController = null;
		this.databaseLoaded = false;
		this.database = null;
	},
	load: function(request, single)
	{
		this.rawRequest = request;

		this.io = new Barakus_Helpers_FileHelper();

		this.request = new Barakus_Core_Request(request, single);
		this.actionController = new Barakus_Core_ActionController(this.request);
		this.actionController.doAction();
	},
	__include: function(file, e)
	{	
		if (!e && !this.io.fileExists(file))
		{
			opera.postError('File ' + file + ' not exists');
			throw new Error('File ' + file + ' not exists');
		}
		var auxDebug = DEBUG;
		DEBUG = 0;
		BARAKUS_LOAD_SCRIPT(file);
		DEBUG = auxDebug;
	},
	include: function(file)
	{
		this.__include(BARAKUS_PATH + file);
	},
	webInclude: function(file)
	{
		this.__include(WEB_PATH + file);
	},
	write: function(str)
	{
		this.rawRequest.write(str);
	},
	setDatabase(database)
	{
		this.databaseLoaded = true;
		
		this.database = database;
	}
});

function __barakus(request, single)
{
    BARAKUS.load(request, single);
}

var BARAKUS = new Barakus(); 

BARAKUS.__include(BARAKUS_PATH + 'helpers/fileHelper.js', true);

BARAKUS.__include(BARAKUS_PATH + 'core/actionController.js', true);
BARAKUS.__include(BARAKUS_PATH + 'core/model.js', true);
BARAKUS.__include(BARAKUS_PATH + 'core/view.js', true);
BARAKUS.__include(BARAKUS_PATH + 'core/controller.js', true);
BARAKUS.__include(BARAKUS_PATH + 'core/request.js', true);

function BARAKUS_LOAD_SCRIPT(fn) {
	function _safe_reload(fn) {
		var txt = safe_file_get(fn, null);
		if(txt == null) {
			throw new Error("Cannot load "+safe_html(fn));
		} else {
			try {
				var err = eval(txt);
			} catch(err) {
				throw new Error('Syntax error in '+safe_html(fn)+'. No info about lines available...');
			};
		};
	};
	
	/* pretty evil, as docs suggest */
	if (!__DONE_LOADING) { // insurance against loading new modules to running server
		__LOADED_SCRIPTS.push(fn);
		_safe_reload(fn);
	} else {  
//		if(DEBUG) { // don't do it in production
			_safe_reload(fn);
//		};
	};
};